"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 配置文件丢失恢复，备机重建后，主备切换
Create At   : 2020/07/24
Owner       : @li-xin12345
Description :
    1. 备机删除配置文件
    2. 备机重建
    3. 恢复配置文件
    4. 备机重建
    5. 查看主备状态
    6. 主备切换
    新主节点执行以下指令刷新
    7. 查看主备状态
    8. 切换后主节点运行tpcc指令
Expect      :
    1. 执行成功，无返回信息
    2. 执行失败，返回
    3. 执行成功，无返回信息
    4. 执行成功
    5. 执行成功，返回
    6. 返回信息
    7. 原主节点state：Standby Normal
    原备节点state：Primary Normal
    8. 执行成功，返回信息关注
History     :
    modified: 2020/12/09  modified by @wan005,主备切换后增加状态校验，若异常则重建
    modified: 2020/12/09  modified by @wan005;优化脚本，调用commonsh方法；增加主备同步校验
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

logger = Logger()


class IndexFileDamaged(unittest.TestCase):
    primary_sh = CommonSH('PrimaryDbUser')
    standby_1_sh = CommonSH('Standby1DbUser')
    standby_2_sh = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info('----Opengauss_Reliability_Dbsys_Case179.py start----')
        self.rootNode = Node('PrimaryRoot')
        self.primaryNode = Node(node='PrimaryDbUser')
        self.StandbyRoot = Node(node='Standby1Root')
        self.standbyNode = Node(node='Standby1DbUser')
        self.INIT_PATH = os.path.join(macro.DB_INSTANCE_PATH,
                                      macro.DB_PG_CONFIG_NAME)
        self.BACKUP_PATH = os.path.join(macro.DB_BACKUP_PATH,
                                        macro.DB_PG_CONFIG_NAME)
        self.constant = Constant()
        self.com = Common('PrimaryDbUser')

    def test_Index_file_damaged(self):
        # 备机删除配置文件
        logger.info('----1. 备机删除配置文件----')
        excute_cmd = f'mv {self.INIT_PATH} {macro.DB_BACKUP_PATH}'
        logger.info(excute_cmd)
        msg = self.StandbyRoot.sh(excute_cmd).result()
        logger.info(msg)
        self.assertNotIn(self.constant.SQL_WRONG_MSG[1], msg)

        logger.info('----2.备机重建----')
        build_msg = self.standby_1_sh.executeGsctl(
            'build', self.constant.BUILD_FAIL_MSG_OPEN, '-b full')
        logger.info(build_msg)
        self.assertTrue(build_msg)

        logger.info('----3. 恢复配置文件----')
        excute_cmd = f'mv {self.BACKUP_PATH} {macro.DB_INSTANCE_PATH}'
        logger.info(excute_cmd)
        msg = self.StandbyRoot.sh(excute_cmd).result()
        logger.info(msg)
        self.assertNotIn(self.constant.SQL_WRONG_MSG[1], msg)

        logger.info('----4. 备机重建----')
        build_msg = self.standby_1_sh.executeGsctl(
            'build', self.constant.REBUILD_SUCCESS_MSG, '-b full')
        logger.info(build_msg)
        self.assertTrue(build_msg)

        logger.info('----查看主机query，同步是否正常-----')
        self.primary_sh.check_location_consistency('primary', 3)

        logger.info('----5. 查看主备状态-----')
        status = self.primary_sh.getDbClusterStatus('status')
        self.assertTrue(status)

        logger.info('----6. 主备切换----')
        switch_result = self.standby_1_sh.executeGsctl(
            'switchover', self.constant.SWITCH_SUCCESS_MSG)
        self.assertTrue(switch_result)

        logger.info('----进行refresh----')
        refresh_msg = self.standby_1_sh.exec_refresh_conf()
        self.assertTrue(refresh_msg)

        logger.info('---- 7. 查看主备状态-----')
        status = self.primary_sh.getDbClusterStatus('status')
        self.assertTrue(status)

        result = self.primary_sh.check_whether_need_build()
        if result:
            result = self.primary_sh.buildStandby()
            self.assertIn(self.constant.REBUILD_SUCCESS_MSG, result)

        logger.info('----8.还原主备，原主机进行switchover----')
        switch_result = self.primary_sh.executeGsctl(
            'switchover',
            self.constant.SWITCH_SUCCESS_MSG)
        self.assertTrue(switch_result)
        logger.info('----进行refresh----')
        refresh_msg = self.primary_sh.exec_refresh_conf()
        self.assertTrue(refresh_msg)

        logger.info('----查看主备是否同步----')
        self.primary_sh.check_location_consistency('primary', 3)

        logger.info('----查询主备状态-----')
        status = self.primary_sh.getDbClusterStatus('status')
        self.assertTrue(status)

        logger.info('----执行TPCC----')
        tpcc_result = self.com.startTPCC(self.rootNode, macro.TPCC_PATH,
                                         f'. runBenchmark.sh '
                                         f'{macro.TPCC_PROPS_FILENAME}')
        logger.info(tpcc_result)
        self.assertIn(self.constant.TPCC_SUCCESS_MSG, tpcc_result)

        logger.info('----查看主备是否同步----')
        self.primary_sh.check_location_consistency('primary', 3)

    def tearDown(self):
        logger.info('-----后置处理------')
        excute_cmd = f'mv {self.BACKUP_PATH} {macro.DB_INSTANCE_PATH}'
        logger.info(excute_cmd)
        msg = self.standbyNode.sh(excute_cmd).result()
        logger.info(msg)
        result = self.primary_sh.check_whether_need_build()
        if result:
            result = self.standby_1_sh.buildStandby()
            self.assertIn(self.constant.REBUILD_SUCCESS_MSG, result)

        host_name = self.rootNode.sh('hostname').result()
        result = self.primary_sh.check_whether_need_switch(host_name)
        if result:
            result = self.primary_sh.executeGsctl(
                'switchover', self.constant.SWITCHOVER_SUCCESS_MSG)
            logger.info(result)
            result = self.primary_sh.exec_refresh_conf()
            logger.info(result)

        logger.info('----Reliability_Dbsys_Case179执行完成----')
